import { getArticleList } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { useHistory } from 'react-router-dom'
import ArticleItem from '../ArticleItem'

import styles from './index.module.scss'

const ArticleList = () => {
  const history = useHistory()
  const channelId = useSelector((state: RootState) => state.home.active)
  const dispatch = useDispatch()
  const [hasMore, setHasMore] = useState(true)
  async function loadMore () { // 无限滚动
    await dispatch(getArticleList(channelId, timestamp))
    if (articles.length >= 50) {
      setHasMore(false)
    }
  }
  const { articles = [], timestamp } = useSelector((state: RootState) => state.home.channelArticles[state.home.active] || {})
  return (
    <div className={styles.root}>
      <PullToRefresh
        onRefresh={async () => {
          await dispatch(getArticleList(channelId, Date.now() + '', true))
        }}
      >
        {/* 文章列表中的每一项 */}
        {articles.map((item, ind) => (
          <div key={ind} className="article-item" onClick={() => history.push(`/article/${item.art_id}`)}>
            <ArticleItem item={item} />
          </div>
        ))}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
